package com.sherman.juel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class JuelFlowFunction {


    /**
     * 包含元素
     * @param list
     * @param ele
     * @return
     */
    public boolean contains(List list, Object ele){
        if (Objects.isNull(list)){
            throw new IllegalArgumentException();
        }
        if (list.size() == 0 || ele == null) {
            return false;
        }
        boolean isNumber = list.get(0) instanceof Number || ele instanceof Number;
        if (isNumber) {
            List<String> collect = (List<String>) list.stream().map(String::valueOf).collect(Collectors.toList());
            return contains(collect, String.valueOf(ele));
        }
        return list.contains(ele);
    }

    /**
     * 包含子串
     * @param str
     * @param substr
     * @return
     */
    public boolean indexof(String str, String substr){
        if (Objects.isNull(str) || Objects.isNull(substr)){
            throw new RuntimeException();
        }
        return str.contains(substr);
    }

    /**
     * 存在于list
     * @param ele
     * @param list
     * @return
     */
    public boolean in(Object ele, List list){
        if (Objects.isNull(list)){
            throw new RuntimeException();
        }
        return list.contains(ele);
    }

    /**
     * 组装list
     * @param items
     * @return
     */
    public static List list(Object... items){
        if (Objects.isNull(items)){
            throw new RuntimeException();
        }
        List list = new ArrayList();
        for (Object obj : items){
            list.add(obj);
        }
        return list;
    }

    public boolean anyEq(Object srcObject, String subPropertyName, String matchValue) {
        if (srcObject instanceof List) {
            List<Object> fieldValues = getFieldValueForArray((List) srcObject, subPropertyName);
            return fieldValues.stream().anyMatch(fieldValue -> equals(fieldValue, matchValue));
        }

        Object fieldValue = getFieldValue(srcObject, subPropertyName);
        return equals(fieldValue, matchValue);
    }

    private List<Object> getFieldValueForArray(List srcObject, String subPropertyName) {
        List<Object> valueArray = new ArrayList<>();
        for (Object o : srcObject) {
            Object fieldValue = getFieldValue(o, subPropertyName);
            if (fieldValue != null) {
                valueArray.add(fieldValue);
            }
        }
        return valueArray;
    }

    private Object getFieldValue(Object srcObject, String subPropertyName) {
        return ((Map) srcObject).get(subPropertyName);
    }

    private boolean equals(Object srcValue, String matchValue) {
        return matchValue != null && matchValue.equals(srcValue.toString());
    }

}
